import requests
from bs4 import BeautifulSoup
from datetime import datetime
from spiders.db.dbmysql import engine, session
from sqlalchemy import Table, MetaData

from spiders.dto.book import Book

metadata = MetaData()


# 爬取小说详情页
def save_novel_to_db(novel_data):
    pass


# 动态执行代码
def dynamic_execution(soup, field_name, code):
    try:
        # exec() 执行代码并创建变量
        local_variables = {}
        exec(code, {'soup': soup}, local_variables)
        # 从 local_variables 中获取执行后的结果
        return local_variables.get(field_name, 'N/A')
    except Exception as e:
        return f"Error executing code: {str(e)}"


def scrape_novel_detail(task):
    # 假设任务字典中包含小说详情页的URL
    if task.book_detail_url is None:
        # 跳过没有URL的任务
        return
    bookDetailUrl = task.book_detail_url.replace("{bookId}", task.source_book_id)
    response = requests.get(bookDetailUrl)
    if response.status_code != 200:
        print(f"Error fetching URL: {bookDetailUrl}")
        return
    soup = BeautifulSoup(response.content, 'html.parser')
    # 1. 获取书籍名称
    book_name_code = "book_name =" + task.book_name_pattern
    book_name = dynamic_execution(soup, 'book_name', book_name_code)
    print("书名:", book_name)
    # 2. 获取作者名称
    author_code = "author =" + task.author_name_pattern
    author = dynamic_execution(soup, 'author', author_code)
    # 3. 获取类型和连载状态
    type_status_code = "type_status =" + task.status_pattern
    type_status = dynamic_execution(soup, 'type_status', type_status_code)
    # 4. 获取阅读人数
    visit_count_code = "visit_count =" + task.visit_count_pattern
    visit_count = dynamic_execution(soup, 'visit_count', visit_count_code)
    # 5. 获取书籍简介
    book_desc_code = "book_desc =" + task.visit_count_pattern
    book_desc = dynamic_execution(soup, 'book_desc', book_desc_code)
    # 6. 获取封面图片URL
    pic_url_code = "pic_url =" + task.visit_count_pattern
    pic_url = dynamic_execution(soup, 'pic_url', pic_url_code)
    # self.word_count = word_count  # 字数
    # self.last_index_id = last_index_id  # 最新章节ID
    # self.last_index_name = last_index_name  # 最新章节名称
    # self.last_index_update_time = last_index_update_time  # 最新章节更新时间
    # self.is_vip = is_vip  # 是否为VIP小说
    # self.update_time = update_time  # 更新时间
    # self.create_time = create_time  # 创建时间
    # self.crawl_source_id = crawl_source_id  # 爬取来源ID
    # self.crawl_book_id = crawl_book_id  # 爬取小说ID
    # self.crawl_last_time = crawl_last_time  # 最后爬取时间
    # self.crawl_is_stop = crawl_is_stop  # 爬取是否停止
    # 输出获取的信息
    book = Book()
    book.book_name = book_name
    book.author_name = author
    book.pic_url = pic_url
    book.book_desc = book_desc
    book.visit_count = visit_count
    book.status = type_status
    book.update_time = datetime.now()
    book.create_time = datetime.now()

    return book
